package com.zboin.framework.serve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zboin.common.domain.AjaxResult;
import com.zboin.common.domain.LoginBody;
import com.zboin.common.exception.LoginException;
import com.zboin.domain.LoginUser;
import com.zboin.domain.UserInfo;
import com.zboin.utils.EncryptUtil;
import com.zboin.mapper.UserInfoMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author zhboom
 * @date 2025/6/8 21:38
 */
@Slf4j
@Service
public class LoginServe {

    @Value("${zboin.password.salt}")
    private String salt;

    private final TokenServe tokenServe;
    private final UserInfoMapper userInfoMapper;

    public LoginServe(TokenServe tokenServe, UserInfoMapper userInfoMapper) {
        this.tokenServe = tokenServe;
        this.userInfoMapper = userInfoMapper;
    }

    public AjaxResult login(LoginBody loginBody) {
        // 登录信息校验
        LoginUser loginUser = loginUserCheck(loginBody);

        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setUsername(loginBody.getUsername());
        log.info("user [{}] login succeed.", loginBody.getUsername());

        return AjaxResult.success("登录成功", tokenServe.createToken(loginUser));
    }

    /**
     * 退出登录
     */
    public void logout() {
        // 拿到请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String token = tokenServe.getToken(request);
        log.info("user logout, clear token [{}]", token);
        if (!StringUtils.hasText(token)) return;

        // 清除 token
        tokenServe.clearTokenCache(token);
    }

    private LoginUser loginUserCheck(LoginBody body) {
        log.debug("login user valid, {}", body.getUsername());
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("name", body.getUsername());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if (userInfo == null) {
            log.error("username: [{}] or password: [{}] is invalid.", body.getUsername(), body.getPassword());
            throw new LoginException(1003, "login failed. username or password is incorrect.");
        }
        if (!userInfo.getPassword().equals(EncryptUtil.encryptMd5(body.getPassword(), salt))) {
            log.error("username: [{}] or password is invalid.", body.getUsername());
            throw new LoginException(1003, "login failed. username or password is incorrect.");
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUserInfo(userInfo);

        return loginUser;
    }
}
